Functions in Python

We have already used few of the functions in Python, such as, len, random, range, etc.

Functions could be considered a black box object, which given some input gives back some output. So for example, len takes an object as its input and returns its length as output.

Defining your own function

A function definition starts with the keyword def followed by the function name, and the set of expected input parameters enclosed between a pair of parenthesis. For example:


In [1]:
def get_simple_interest(p, r, t):
    return p * r * t / 100.0

In [5]:
get_simple_interest(10000, 10, 1)


Out[5]:
1000.0

Exercise:

  • Write a function to calculate factorial of a number -- bonus points of writing it recursively and testing it with large values ;-)
  • Write a function which takes a string as input and prints it in reverse order

Returning multiple values from a function

Python allows returning multiple values from a function, let's see how


In [6]:
def get_perimeter_and_area(r):
    perimieter = 2 * 3.14 * r
    area = 3.14 * r ** 2
    return perimieter, area

In [8]:
perimeter, area = get_perimeter_and_area(10)
print 'Perimeter = ' + str(perimeter) 
print 'Area = ' + str(area)


Perimeter = 62.8
Area = 314.0

You can return any number of values from a function and read them in that order when you call it

Python wraps these multiple return values in the form of a tuple and returns to the caller